<?php

	//------------------------------------------------------------------
	//		Tpl proxy placeholder. 
	//		By default, it uses Smarty as template engine.
	//------------------------------------------------------------------

	interface i_tpl_wrapper {
		public function assign($var, $value);
		public function fetch($template_name);
		public function set_template_dir($dir);
	}

	//implement i_tpl_wrapper
	//OVERRIDE tpl::__construct if nececery

	class tpl extends service implements i_tpl_wrapper {
		
		private $__poi;

		public function __construct(){
			$cfg = context::get("config");
			
			if (UTILS_in_array($cfg["libs"],"Smarty")){
				$this->__poi = new smarty_tpl();
			}else{
				$this->__poi = new dummy_tpl();
			}
			
		}
		
		public function assign($var, $value){
			$this->__poi->assign($var, $value);
		}
		
		public function fetch($template_name){
			return $this->__poi->fetch($template_name);
		}
		
		public function set_template_dir($dir){
			return $this->__poi->set_template_dir($dir);
		}
	}
	
	class smarty_tpl implements i_tpl_wrapper {
		private $smarty;
		
		public function __construct(){
			$root = context::get("path")->get_root();
			
			$this->smarty = new Smarty();
			$this->smarty->template_dir = $root._DRS."modules"._DRS.context::get("request")->get_module_name();
			$this->smarty->compile_dir 	= $root._DRS."tmp";
			#$this->smarty->cache_dir 	= $root._DRS."cache";
			
			
			@chmod($root._DRS."tmp",0777);
			#chmod($root._DRS."cache",0777);
			
			//TODO: caching support (?)
		}
		
		public function assign($var, $value){
			$this->smarty->assign($var, $value);
		}
		
		public function fetch($template_name){	
			//Debug only. Disable me later
			if ($template_name == "__undefined.tpl"){
				throw new Core_Exception("Trying to run undefined module!",EX_NONCRIT);
			}
			
			#context::io()->debug("fetching ".$template_name);
			try {			
				$html = $this->smarty->fetch($template_name);
			}
			catch (Exception $e){
				throw new Core_Exception("tpl exception: {$e->getMessage()}",EX_NONCRIT);
			}
			
			#context::io()->debug("tpl::fetch() - returned html: {$html}");
			
			return $html;
		}
		public function set_template_dir($dir){
			$this->smarty->template_dir = $dir;	
		}
	}
	
	class dummy_tpl implements i_tpl_wrapper {
		public function assign($var, $value){
			context::io()->debug("dummy_tpl::assign()",IO_DEBUG_NOTICE);
		}
		
		public function fetch($template_name){
			context::io()->debug("dummy_tpl::fetch()",IO_DEBUG_NOTICE);
		}
		
		public function set_template_dir($dir){
		}
	}

?>
